package lumingweihua.future.cn.lumingweihua;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewStub;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import lumingweihua.future.cn.baselibgxh.base.BaseActivity;
import lumingweihua.future.cn.baselibgxh.base.MyApplication;
import lumingweihua.future.cn.baselibgxh.dialog.YesOrNoDialog;
import lumingweihua.future.cn.baselibgxh.dialog.YesOrNoDialogEntity;
import lumingweihua.future.cn.baselibgxh.network.AbstractRequest;
import lumingweihua.future.cn.baselibgxh.network.BeanRequest;
import lumingweihua.future.cn.baselibgxh.network.NetworkManager;
import lumingweihua.future.cn.baselibgxh.network.ReqTag;
import lumingweihua.future.cn.baselibgxh.network.entity.DefaultMamahaoServerError;
import lumingweihua.future.cn.baselibgxh.network.entity.MamaHaoServerError;
import lumingweihua.future.cn.baselibgxh.utils.CommonUtils;
import lumingweihua.future.cn.baselibgxh.utils.DownloadHelper;
import lumingweihua.future.cn.baselibgxh.utils.SharedPreference;
import lumingweihua.future.cn.lumingweihua.guide.FirstGuideActivity;
import lumingweihua.future.cn.lumingweihua.home.HomeFragment;
import lumingweihua.future.cn.lumingweihua.home.cheyuan.RobOrderActivity;
import lumingweihua.future.cn.lumingweihua.information.InformationFragment;
import lumingweihua.future.cn.lumingweihua.order.OrderFragment;
import lumingweihua.future.cn.lumingweihua.person.LoginActivity;
import lumingweihua.future.cn.lumingweihua.person.MyFragment;
import lumingweihua.future.cn.lumingweihua.person.domain.PersonData;
import lumingweihua.future.cn.lumingweihua.release.ReleaseCarActivity;
import lumingweihua.future.cn.lumingweihua.release.ReleaseGoodsActivity;


public class MainActivity extends BaseActivity implements AMapLocationListener {

    private Fragment[] fragmentPages;
    private TextView[] tv_tabs;
    private int[] tab_icons;
    public static MainActivity instance;
    public List<List<String>> citys = new ArrayList<>();
    public List<String> provinces = new ArrayList<>();
    public PersonData personData;
    private AMapLocationClient mlocationClient;//定位客户端
    public AMapLocation aMapLocation;
    private View view_public;
    private ImageView iv_huoyuan;
    private ImageView iv_cheyuan;
    private MyFragment myFragment;

    @Override
    protected void initView() {
        // TODO Auto-generated method stub
        setContentView(R.layout.activity_main);
//		requestVersion();
        view_public = findViewById(R.id.view_public);
        iv_huoyuan = findImageView(R.id.iv_huoyuan);
        iv_cheyuan = findImageView(R.id.iv_cheyuan);
        requestPersonData();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_HOME) {

            //屏蔽之后的操作
            showToast("home键");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private HomeFragment homeFragment;
    public String cityName = "菏泽市";
    public String provinceName = "山东省";
    private View vs;

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    protected void initData() {
        // TODO Auto-generated method stub
        //fragment页面
        instance = this;

        if(SharedPreference.getBoolean(context,"isfirst",true)){
            vs = ((ViewStub) findViewById(R.id.vs_img)).inflate();
            ((ImageView)vs.findViewById(R.id.logo)).setImageResource(R.drawable.guide_01);
            ((ImageView)vs.findViewById(R.id.logo)).setOnClickListener(this);
        }

        homeFragment = new HomeFragment();
        fragmentPages = new Fragment[]{homeFragment, new OrderFragment(), new InformationFragment(), myFragment = new MyFragment()};

        //底部tab
        tv_tabs = new TextView[]{findTextView(R.id.tab_home),
                findTextView(R.id.tab_order),
                findTextView(R.id.tab_message),
                findTextView(R.id.tab_my)};

        for (TextView tv : tv_tabs)
            tv.setOnClickListener(this);

        findViewById(R.id.tab_publish).setOnClickListener(this);
        findViewById(R.id.view_mask).setOnClickListener(this);
        iv_huoyuan.setOnClickListener(this);
        iv_cheyuan.setOnClickListener(this);

        //底部tab图片资源id
        tab_icons = new int[]{R.drawable.ic_bottombar_1_n,
                R.drawable.ic_bottombar_2_n,
                R.drawable.ic_bottombar_3_n,
                R.drawable.ic_bottombar_4_n,
                R.drawable.ic_bottombar_1_s,
                R.drawable.ic_bottombar_2_s,
                R.drawable.ic_bottombar_3_s,
                R.drawable.ic_bottombar_4_s};

        // 添加显示第一个fragment
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, fragmentPages[0]).commit();

//		requestVersion();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE}, BAIDU_READ_PHONE_STATE);
        } else {
            initLocation();
        }


        initCityPickerViewDatas();
    }

    private static final int BAIDU_READ_PHONE_STATE = 100;

    //Android6.0申请权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case BAIDU_READ_PHONE_STATE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                    initLocation();
                } else {
                    // 没有获取到权限，做特殊处理
                    Toast.makeText(getApplicationContext(), "获取位置权限失败，请手动开启", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    private void initLocation() {
        if (aMapLocation != null) {
            cityName = aMapLocation.getCity();
            provinceName = aMapLocation.getProvince();
        } else {
            mlocationClient = new AMapLocationClient(this);
            AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//        mLocationOption.setInterval(5000);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);

            mlocationClient.startLocation();
        }
    }

    /**
     * 初始化省市数据
     */
    private void initCityPickerViewDatas() {
        ProvinceBeans pbs = new Gson().fromJson(getString(R.string.provinces), ProvinceBeans.class);
        for (CityBeans cb : pbs.provinces) {
            provinces.add(cb.provinceName);
            List<String> cityDatas = new ArrayList<>();
            for (CityData cd : cb.citys)
                cityDatas.add(cd.citysName);
            citys.add(cityDatas);
        }

        List<String> c = new ArrayList<>();
        c.add("全部");
        provinces.add(0,"全部");
        citys.add(0,c);
    }

    private int guidePos;
    @Override
    protected void processClick(View v) {
        switch (v.getId()) {
            case R.id.logo:
                guidePos++;
                if(guidePos==1){
                    ((ImageView)vs.findViewById(R.id.logo)).setImageResource(R.drawable.guide_02);
                }else if(guidePos==2){
                    ((ImageView)vs.findViewById(R.id.logo)).setImageResource(R.drawable.guide_03);
                }else if(guidePos==3){
                    ((ImageView)vs.findViewById(R.id.logo)).setImageResource(R.drawable.guide_04);
                }else{
                    SharedPreference.saveToSP(context,"isfirst",false);
                    vs.setVisibility(View.GONE);
                }

                break;
            case R.id.tab_home:
                changeTab(0);
                break;
            case R.id.tab_order:
                changeTab(1);
                break;
            case R.id.tab_message:
                changeTab(2);
                break;
            case R.id.tab_my:
                changeTab(3);
                myFragment.refreshInfo();
                break;
            case R.id.tab_publish:
                view_public.setVisibility(View.VISIBLE);
                ScaleAnimation animation = new ScaleAnimation(0.9f,1.25f,0.9f,1.25f, Animation.RELATIVE_TO_SELF,0.5f, Animation.RELATIVE_TO_SELF,0.5f);
                animation.setDuration(350);
                iv_huoyuan.setAnimation(animation);
                iv_cheyuan.setAnimation(animation);
                break;
            case R.id.view_mask:
                view_public.setVisibility(View.GONE);
                break;
            case R.id.iv_huoyuan:
                //发布货源
                if (MyApplication.getInstance().isUserLogin()) {
                    startActivityForResult(new Intent(context, ReleaseGoodsActivity.class), 10);
                    view_public.setVisibility(View.GONE);
                } else
                    jumpToNextActivity(LoginActivity.class, false);

                break;
            case R.id.iv_cheyuan:
                //发布车源
                if (MyApplication.getInstance().isUserLogin()) {
                    startActivityForResult(new Intent(context, ReleaseCarActivity.class), 11);
                    view_public.setVisibility(View.GONE);
                } else
                    jumpToNextActivity(LoginActivity.class, false);

                break;

            default:
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10 && resultCode == RESULT_OK) {
            homeFragment.refresh(1);
        } else if (requestCode == 11 && resultCode == RESULT_OK) {
            homeFragment.refresh(0);
        } else if (requestCode == MyFragment.REQUEST_ID) {
            myFragment.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }

    private int currentTabIndex;

    /**
     * 切换tab
     *
     * @param index
     */
    @SuppressWarnings("deprecation")
    public void changeTab(int index) {
        //当前tab不执行操作
        if (currentTabIndex == index)
            return;

        //切换之前选中tab的图标和文字颜色
        tv_tabs[currentTabIndex].setTextColor(getResources().getColor(
                R.color.C1));
        tv_tabs[currentTabIndex].setCompoundDrawables(null, CommonUtils.GetDrawable(
                context, tab_icons[currentTabIndex]), null, null);
        //切换当前选中tab的图标和文字颜色
        tv_tabs[index].setTextColor(getResources().getColor(
                R.color.title_bg));
        tv_tabs[index].setCompoundDrawables(null, CommonUtils.GetDrawable(
                context, tab_icons[index + tv_tabs.length]), null, null);

        FragmentTransaction ft = getSupportFragmentManager()
                .beginTransaction();
        ft.hide(fragmentPages[currentTabIndex]);
        if (!fragmentPages[index].isAdded()) {
            ft.add(R.id.fragment_container, fragmentPages[index]);
        }
        ft.show(fragmentPages[index]).commit();

        currentTabIndex = index;

    }


    private int mBackKeyPressedTimes = 0;

    @Override
    public void onBackPressed() {

        if (homeFragment.isShowingMask()) {
            homeFragment.dismissMask();
            return;
        }

        if (view_public.getVisibility() == View.VISIBLE) {
            view_public.setVisibility(View.GONE);
            return;
        }

        if (mBackKeyPressedTimes == 0) {
            showToast(getString(R.string.exit_app));
            mBackKeyPressedTimes = 1;
            new Thread() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        mBackKeyPressedTimes = 0;
                    }
                }
            }.start();
            return;

        } else {
//            AppManager.getInstance().finishAllActivity();
            finish();
        }
        super.onBackPressed();
    }

    private final int REQUEST_VERSION = 1;
    /**
     * 请求标识
     **/
    private final String REQUEST_TAG = "HomeFragmentBase";
    private final int REQUEST_BANNER = 1;
    private final int REQUEST_PERSON = 2;

    /**
     * 版本信息
     */
    private void requestVersion() {
//		showProgressBar(null);

        BeanRequest<UpdateVersion, DefaultMamahaoServerError> req = new BeanRequest<UpdateVersion, DefaultMamahaoServerError>(
                context,
                "",
                this, UpdateVersion.class, false);

        req.setParam("apiCode", "_app_check_001");
        req.setParam("platform", "101");

        //获取token
        String token = NetworkManager.getInstance().getPostToken(req.getParam());
        req.setParam("token", token);

        addRequestQueue(req, REQUEST_VERSION);
    }

    /**
     * 公共个人信息
     */
    private void requestPersonData() {
//		showProgressBar(null);

        BeanRequest<PersonData, DefaultMamahaoServerError> req = new BeanRequest<>(
                context,
                "",
                this, PersonData.class);

        req.setParam("apiCode", "_userinfo_001");
        req.setParam("userToken", MyApplication.getInstance().getUserToken());

        //获取token
        String token = NetworkManager.getInstance().getPostToken(req.getParam());
        req.setParam("token", token);

        addRequestQueue(req, REQUEST_PERSON);
    }

    @Override
    protected void onResponseSuccess(ReqTag tag, Object data) {
        // TODO Auto-generated method stub
        super.onResponseSuccess(tag, data);
        switch (tag.getReqId()) {
            case REQUEST_VERSION:
                //版本信息
                UpdateVersion updateVersion = (UpdateVersion) data;
                //版本信息
                if (!updateVersion.getApp_version().equals(CommonUtils.getAppVersionCode(context)))
                    alertUpdate(updateVersion.getDescription(), updateVersion.getDownloadurl(), updateVersion.getCode());
                break;
            case REQUEST_PERSON:
                personData = (PersonData) data;
                break;

            default:
                break;
        }
    }

    @Override
    protected void onResponseFailure(ReqTag tag, MamaHaoServerError error,
                                     AbstractRequest.MamaHaoError clientError) {
        // TODO Auto-generated method stub
        super.onResponseFailure(tag, error, clientError);
        switch (tag.getReqId()) {
            case REQUEST_PERSON:
                personData = new PersonData();
                personData.setInviteTime("1");
                break;

            default:
                break;
        }
    }

    public class UpdateVersion {
        private String app_version;
        private String downloadurl;
        private String description;
        private String code;

        public String getApp_version() {
            return app_version;
        }

        public void setApp_version(String app_version) {
            this.app_version = app_version;
        }

        public String getDownloadurl() {
            return downloadurl;
        }

        public void setDownloadurl(String downloadurl) {
            this.downloadurl = downloadurl;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

    }


    private ProgressDialog progressDialog;
    private File file;

    protected void alertUpdate(String msg, final String url, String code) {
        // TODO Auto-generated method stub
        new YesOrNoDialog(context, new YesOrNoDialogEntity("版本更新", "取消", "去更新"), new YesOrNoDialog.OnYesOrNoDialogClickListener() {

            @Override
            public void onYesOrNoDialogClick(YesOrNoDialog.YesOrNoType yesOrNoType) {
                // TODO Auto-generated method stub
                switch (yesOrNoType) {
                    case BtnOk:
                        final Message msg = new Message();
                        progressDialog = new ProgressDialog(MainActivity.this);
                        progressDialog.setTitle("正在下载");
                        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        progressDialog.show();
                        new Thread() {
                            public void run() {
                                file = new DownloadHelper().downloadNewVersion(url, progressDialog);
                                progressDialog.dismiss();
                                if (file == null) {
                                    msg.what = FAIL_DOWNLOAD;
                                    handler.sendMessage(msg);
                                } else {
                                    msg.what = INSTALL;
                                    handler.sendMessage(msg);
                                }
                            }

                            ;
                        }.start();
                        break;
                    case BtnCancel:

                        break;

                    default:
                        break;
                }
            }
        }).show();
//		AlertDialog.Builder builder = new AlertDialog.Builder(this);
//		builder.setTitle("版本更新").setMessage(msg)
//				.setCancelable(false);
//
//		builder.setPositiveButton("更新", new OnClickListener() {
//
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				// TODO Auto-generated method stub
//				
//			}
//
//		});
//		
//		if(!"3".equals(code)){
//			builder.setNegativeButton("下次", new OnClickListener() {
//
//				@Override
//				public void onClick(DialogInterface dialog, int which) {
//					// TODO Auto-generated method stub
//				}
//			});
//		}
//		
//
//		AlertDialog dialog = builder.create();
//		dialog.show();
    }

    private final int ALERT_UPDATE = 0;
    private final int CONN_ERROR = 1;
    private final int INSTALL = 2;
    private final int FAIL_DOWNLOAD = 3;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case INSTALL:
                    install();
                    break;
                case CONN_ERROR:
                    Toast.makeText(getApplicationContext(), "网络连接失败", Toast.LENGTH_SHORT).show();
                    break;
                case FAIL_DOWNLOAD:
                    Toast.makeText(getApplicationContext(), "下载失败", Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };

    protected void install() {
        // TODO Auto-generated method stub
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }

    public class ProvinceBeans {
        public List<CityBeans> provinces;
    }

    public class CityBeans {
        public String provinceName;
        public List<CityData> citys;
    }

    public class CityData {
        public String citysName;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        // TODO Auto-generated method stub
        if (aMapLocation != null) {
            if (aMapLocation != null
                    && aMapLocation.getErrorCode() == 0) {

                this.aMapLocation = aMapLocation;
                provinceName = aMapLocation.getProvince();
                cityName = aMapLocation.getCity();

                mlocationClient.stopLocation();
            } else {
//                mlocationClient.stopLocation();
//                Toast.makeText(this,"定位失败",Toast.LENGTH_LONG).show();
            }
        }
    }

}
